package com.ychen.ruijee.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.javafx.webkit.ThemeClientImpl;
import com.ychen.ruijee.bean.Category;
import com.ychen.ruijee.bean.Dish;
import com.ychen.ruijee.bean.DishFlavor;
import com.ychen.ruijee.common.R;
import com.ychen.ruijee.dto.DishDto;
import com.ychen.ruijee.service.CategoryService;
import com.ychen.ruijee.service.DishFlavorService;
import com.ychen.ruijee.service.DishService;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.awt.datatransfer.FlavorEvent;
import java.lang.management.ThreadInfo;
import java.sql.Time;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ychen@gotop.cn
 * @date 2024-06-02 21:45
 */
@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {

    @Resource
    private DishService dishService;

    @Resource
    private CategoryService categoryService;

    @Resource
    private DishFlavorService dishFlavorService;

    @Resource
    private RedisTemplate redisTemplate;
    /**
     * 新增 菜品信息 菜品的口味 单独存放
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> saveDish(@RequestBody DishDto dishDto){
        boolean saveFlag = dishService.saveDish2Flavor(dishDto);
        return saveFlag ? R.success("添加菜品信息成功") : R.error("添加菜品信息失败");

    }

    @GetMapping("/page")
    public R<Page<DishDto>> dishPageInfo(@RequestParam(defaultValue = "1") Integer page,
                                         @RequestParam(defaultValue = "10") Integer pageSize,
                                         String name){
        Page<DishDto> result = dishService.dishPageInfo(page,pageSize,name);
        return R.success(result);
    }

    /**
     * 修改菜品信息时候 数据回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> getDishDto (@PathVariable Long id){
        DishDto dishDto = dishService.getDishDto(id);
        return R.success(dishDto);
    }

    /**
     * 修改菜品信息
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> saveUpdateDish(@RequestBody DishDto dishDto){
        boolean flag = dishService.saveUpdateDish(dishDto);
        return flag ? R.success("修改数据成功") : R.error("修改数据失败");

    }

    @GetMapping("/list")
    public R<List<DishDto>> findDishByCategoryId(Dish dish){
        log.info("【dish is 】", dish.toString());
        // 构造 redis 中得 key
        String redisKey = "dish_"+ dish.getCategoryId()+"_"+dish.getStatus();// dish_12345678_1
        // 先从 redis中查询
        if(redisTemplate.hasKey(redisKey)){
            log.info("从redis中 读取 ");
            String jsonStr = (String) redisTemplate.opsForValue().get(redisKey);
            List list = JSON.parseObject(jsonStr, List.class);
            return R.success(list);

        }
        //--------------
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        // 根据 菜品id 去查 菜品
        wrapper.eq(dish.getCategoryId()!=null,Dish::getCategoryId,dish.getCategoryId());
        wrapper.like(dish.getName()!=null,Dish::getName,dish.getName());
        // 添加条件 为客户端查询准备
        wrapper.eq(dish.getStatus()!=null, Dish::getStatus,dish.getStatus());
        List<Dish> list = dishService.list(wrapper);
        // 循环遍历
        List<DishDto> dishDtoList = list.stream().map((item)->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            // 改造 客户端 需要根据 菜品分类id 和 菜品 id 查询出所属分类名称和 菜品的口味信息 封装到 DishDto 对象中
            Category category = categoryService.getById(item.getCategoryId());
            dishDto.setCategoryName(category == null ? "未知":category.getName());
            // 查询口味信息
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId,item.getId());
            List<DishFlavor> flavors = dishFlavorService.list(queryWrapper);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());
         // 菜品信息不在数据库中 存在 查完库后 将数据写入到 redis 中去
        redisTemplate.opsForValue().set(redisKey,JSON.toJSONString(dishDtoList),3600, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
